package com.fcy.musicplayer.util

import android.content.Context
import android.content.SharedPreferences
import android.text.TextUtils

import kotlin.reflect.KProperty

private const val SP_NAME_USER = "user"
private const val SP_KEY_PHONE = "phone"

/**
 * 保存用户登陆状态
 */
fun Context.saveUserInfo(phone: String): Boolean {
    getSharedPreferences(SP_NAME_USER, Context.MODE_PRIVATE).edit().apply {
        this?.putString(SP_KEY_PHONE, phone)
        return this?.commit() ?: false
    }
}

/**
 * 验证当前是否已经有登录用户
 */
fun Context.isLoginUser(): Boolean {
    getSharedPreferences(SP_NAME_USER, Context.MODE_PRIVATE).apply {
        getString(SP_KEY_PHONE, "").also {
            if (TextUtils.isEmpty(it)) {
                return false
            }
            return true
        }
    }
}

/**
 * 清除登录信息
 */
fun Context.deleteLoginInfo(): Boolean {
    getSharedPreferences(SP_NAME_USER, Context.MODE_PRIVATE).edit().apply {
        this?.putString(SP_KEY_PHONE, "")
        return this?.commit() ?: false
    }
}

class PreDelegate<T>(
    private val default: T,
    private val isCommit: Boolean = false,
    private val sharedPreferences: SharedPreferences
) {
    operator fun getValue(thisRef: Any?, properties: KProperty<*>): T {
        return attain(properties.name, default) ?: default
    }

    operator fun setValue(thisRef: Any?, properties: KProperty<*>, value: T) {
        putIn(properties.name, value)
    }

    private fun attain(name: String, default: T): T? = with(sharedPreferences) {
        val result: Any? = when (default) {
            is Long -> getLong(name, default)
            is String -> getString(name, default)
            is Int -> getInt(name, default)
            is Boolean -> getBoolean(name, default)
            is Float -> getFloat(name, default)
            else -> throw IllegalArgumentException("this type is not supported")
        }
        result as? T
    }

    private fun putIn(name: String, value: T) {
        sharedPreferences.edit().apply {
            when (value) {
                is Long -> putLong(name, value)
                is String -> putString(name, value)
                is Int -> putInt(name, value)
                is Boolean -> putBoolean(name, value)
                is Float -> putFloat(name, value)
                else -> throw IllegalArgumentException("this type is not supported")
            }
            if (isCommit) {
                commit()
            } else apply()
        }
    }

}
